<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Redux</title>
</head>
<body>
    <button id="increment">+1</button>
    <span id="result">0</span>
    <button id="decrement">-1</button>
    <script src="myRedux.js"></script>
    <script src="./middlewares/logger.js"></script>
    <script src="./middlewares/thunks.js"></script>
    <script>
        function enhancer(createStore) {
            return function (reducer, loadedState) {
                var store = createStore(reducer, loadedState)
                console.log(store)
                var dispatch = store.dispatch
                function _dispatch(action) {
                    // 实现的增强dispatch方法
                    // 如果action是一个函数 就将dispatch传递给action 让action执行完异步操作后在执行正常的dispatch方法
                    if (typeof action === 'function') {
                        action(dispatch)
                    } else {
                        // 如果action是一个对象 就正常执行dispatch方法
                        dispatch(action)
                    }
                }

                // 如何
                return {
                    ...store,
                    dispatch: _dispatch
                }
            }
        }

        function counterReducer(state, action) {
            switch (action.type){
                case 'increment':
                    return state + 1
                case 'decrement':
                    return state - 1
                default:
                    return state
            }
        }

        // 实现 将一个一个小的reducer合并为大的reducer
        var rootReducer = combineReducers({ counter: counterReducer })

        const store = createStore(rootReducer, { counter: 10 }, applyMiddleware(logger, thunk))

        store.subscribe(function () {
            document.getElementById('result').innerHTML = store.getState().counter
        })

        // bindActionCreators 调用实现语法
        var actions = bindActionCreators({increment, decrement}, store.dispatch)

        function increment() {
            return { type: 'increment' }
        }

        function decrement() {
            return { type: 'decrement' }
        }

        document.getElementById('increment').onclick = function () {
            // store.dispatch({ type: 'increment' })
            actions.increment()
        }

        document.getElementById('decrement').onclick = function () {
            // store.dispatch({ type: 'decrement' })
            actions.decrement()
        }
    </script>
</body>
</html>